package com.tdkj.service.shop.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.tdkj.dao.shop.IBeanOrderDao;
import com.tdkj.model.base.BaseEntity;
import com.tdkj.model.shop.BeanGood;
import com.tdkj.model.shop.BeanGoodAuction;
import com.tdkj.model.shop.BeanGoodSnapshot;
import com.tdkj.model.shop.BeanOrder;
import com.tdkj.model.shop.BeanOrderConsigneeInfo;
import com.tdkj.model.shop.BeanOrderItem;
import com.tdkj.model.shop.BeanShop;
import com.tdkj.model.shop.BeanShoppingCart;
import com.tdkj.model.shop.BeanShoppingCartItem;
import com.tdkj.model.user.BeanUser;
import com.tdkj.service.BaseService;
import com.tdkj.service.shop.IBeanOrderService;

@Component("orderService")
public class BeanOrderServiceImpl extends BaseService implements
		IBeanOrderService {
	
	private  IBeanOrderDao beanOrderDao;
    
	@Resource
	public void setBeanOrderDao(IBeanOrderDao beanOrderDao) {
		this.beanOrderDao = beanOrderDao;
	}

	public IBeanOrderDao getBeanOrderDao() {
		return beanOrderDao;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BeanOrderItem> getOrderItemsOfBuyer(Long userId) {
		
		List<BeanOrderItem> items = new ArrayList<BeanOrderItem>();
		
		List<BeanOrder> orders =  beanOrderDao.getSession().createCriteria(BeanOrder.class).add(Restrictions.eq("buyer", beanOrderDao.findById(userId, BeanUser.class))).list();
		
		for(BeanOrder order : orders){
			items.addAll(order.getItems());
		}
		return items;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BeanOrder> getOrdersOfBuyer(Long userId) {
		List<BeanOrder> orders =  beanOrderDao.getSession().createCriteria(BeanOrder.class).add(Restrictions.eq("buyer", beanOrderDao.findById(userId, BeanUser.class))).list();
		return orders;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<BeanOrder> getOrdersOfBuyer(Long userId, Integer state) {
		List<BeanOrder> orders =  beanOrderDao.getSession().createCriteria(BeanOrder.class)
		.add(Restrictions.eq("seller", beanOrderDao.findById(userId, BeanUser.class)))
		.add(Restrictions.eq("state", state))
		.list();
		return orders;
	}


	@SuppressWarnings("unchecked")
	@Override
	public List<BeanOrder> getOrdersOfSeller(Long userId) {
		List<BeanOrder> orders =  beanOrderDao.getSession().createCriteria(BeanOrder.class)
		.add(Restrictions.eq("seller", beanOrderDao.findById(userId, BeanUser.class)))
		.list();
		return orders;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BeanOrder> getOrdersOfSeller(Long userId, Integer state) {
		List<BeanOrder> orders =  beanOrderDao.getSession().createCriteria(BeanOrder.class)
		.add(Restrictions.eq("state", state))
		.add(Restrictions.eq("seller", beanOrderDao.findById(userId, BeanUser.class)))
		.list();
		
		return orders;
	}

	@Override
	public List<BeanOrder> create(Long buyerId, BeanOrderConsigneeInfo info) {
		LinkedHashMap<BeanShop,BeanOrder> ordersMap = new LinkedHashMap<BeanShop, BeanOrder>();
		
		BeanUser buyer = beanOrderDao.findById(buyerId, BeanUser.class);
		BeanShoppingCart shoppingCart = buyer.getShoppingCart();
		
		for(BeanShoppingCartItem item : shoppingCart.getItems()){
			
			BeanShop shop = item.getGood().getShop();
			BeanOrder order = ordersMap.get(shop);
			
			if(order == null){
				order = new BeanOrder();
				order.setCode(UUID.randomUUID().toString());
				order.setSeller(shop.getUser());
				order.setBuyer(buyer);
				order.setConsigneeInfo(info);
				order.setState(IBeanOrderService.Constant.STATE_TO_PAY);
				order.setCreateTime(new Timestamp(System.currentTimeMillis()));
				order.setCutoffPaymentTime(new Timestamp(System.currentTimeMillis() + 7L*24*60*60*1000));
				beanOrderDao.save(order);
				
				ordersMap.put(shop, order);
			}
			
			BeanGoodSnapshot snapshot = new BeanGoodSnapshot();
			snapshot.setCode(item.getGood().getCode());
			snapshot.setDetailDescription(item.getGood().getDetailDescription());
			snapshot.setGood(item.getGood());
			snapshot.setImgurl(item.getGood().getImgurl());
			snapshot.setKeywords(item.getGood().getKeywords());
			
			snapshot.setLogisticsType(item.getGood().getLogisticsInfo().getType());
			if("0".equals(item.getGood().getLogisticsInfo().getType())){
				snapshot.setLogisticsPrice(item.getGood().getLogisticsInfo().getEmsPrice());
			}
			snapshot.setName(item.getGood().getName());
			snapshot.setPrice(item.getGood().getPrice());
			
			Map<String,String> properties = new HashMap<String,String>();
			for(String key : item.getGood().getProperties().keySet()){
				properties.put(key, item.getGood().getProperties().get(key));
			}
			snapshot.setProperties(properties);
			snapshot.setPublishTime(item.getGood().getPublishTime());
			snapshot.setQuantity(item.getGood().getQuantity());
			snapshot.setRateOfIncrease(item.getGood().getRateOfIncrease());
			snapshot.setSellType(item.getGood().getSellType());
			snapshot.setState(item.getGood().getState());
			snapshot.setTypeName(item.getGood().getType().getName());
			snapshot.setUser(item.getGood().getUser());
			snapshot.setUseType(item.getGood().getUseType());
			
			beanOrderDao.save(snapshot);
			
			BeanOrderItem orderItem = new BeanOrderItem();
			orderItem.setQuantity(item.getQuantity());
			orderItem.setSnapshot(snapshot);
			orderItem.setGood(item.getGood());
			orderItem.setOrder(order);
			orderItem.setState(0);
			
			beanOrderDao.save(orderItem);
			
			order.getItems().add(orderItem);
		}
		
		List<BeanOrder> orders = new ArrayList<BeanOrder>();
		
		//计费
		for(BeanShop key : ordersMap.keySet()){
			BeanOrder value = ordersMap.get(key);
			BigDecimal totalFee = new BigDecimal("0.00");
			for(BeanOrderItem item : value.getItems()){
				totalFee = totalFee.add(new BigDecimal(item.getQuantity()).multiply(item.getSnapshot().getPrice()));
			}
			value.setTotalFee(totalFee);
			orders.add(value);
		}
		for(BeanShoppingCartItem item : shoppingCart.getItems()){
			beanOrderDao.delete(item);
		}
		return orders;
	}

	@Override
	public void createPay(Long buyerId, Long orderId) {
		
		//会话与订单一致
		BeanOrder order = beanOrderDao.findById(orderId, BeanOrder.class);
		if(order.getBuyer().getId() == buyerId){
			order.setState(IBeanOrderService.Constant.STATE_TO_DELIVERY);
		}
	}

	@Override
	public void createDelivery(Long sellerId, Long orderId) {
		//会话与订单一致
		BeanOrder order = beanOrderDao.findById(orderId, BeanOrder.class);
		if(order.getSeller().getId() == sellerId){
			order.setState(IBeanOrderService.Constant.STATE_TO_RECEIVE);
		}
		
	}

	@Override
	public void createReceive(Long buyerId, Long orderId) {
		//会话与订单一致
		BeanOrder order = beanOrderDao.findById(orderId, BeanOrder.class);
		if(order.getBuyer().getId() == buyerId){
			order.setState(IBeanOrderService.Constant.STATE_SUCCEED);
		}
	}

	@Override
	public List<BeanOrder> create(Long auctionId, Long buyerId,
			BeanOrderConsigneeInfo info, Integer logisticsApproach,
			BigDecimal logisticsPrice) {
		
		
		BeanGoodAuction auction = beanOrderDao.findById(auctionId, BeanGoodAuction.class);
		BeanGood good = auction.getGood();
		BeanShop shop = good.getShop();
		
		if(buyerId != auction.getFinalQuote().getUser().getId()){
			return null;
		}
		
		BeanOrder order = new BeanOrder();
		order.setCode(UUID.randomUUID().toString());
		order.setLogisticsApproach(logisticsApproach);
		order.setLogisticsPrice(logisticsPrice);
		order.setSeller(shop.getUser());
		order.setBuyer(auction.getFinalQuote().getUser());
		order.setConsigneeInfo(info);
		order.setState(IBeanOrderService.Constant.STATE_TO_PAY);
		order.setCreateTime(new Timestamp(System.currentTimeMillis()));
		order.setCutoffPaymentTime(new Timestamp(System.currentTimeMillis() + 7L*24*60*60*1000));
		beanOrderDao.save(order);
				
			
		BeanGoodSnapshot snapshot = new BeanGoodSnapshot();
		snapshot.setCode(good.getCode());
		snapshot.setDetailDescription(good.getDetailDescription());
		snapshot.setGood(good);
		snapshot.setImgurl(good.getImgurl());
		snapshot.setKeywords(good.getKeywords());
			
		snapshot.setLogisticsType(good.getLogisticsInfo().getType());
		if("0".equals(good.getLogisticsInfo().getType())){
			snapshot.setLogisticsPrice(good.getLogisticsInfo().getEmsPrice());
		}
		snapshot.setName(good.getName());
		snapshot.setPrice(good.getPrice());
		
		Map<String,String> properties = new HashMap<String,String>();
		for(String key : good.getProperties().keySet()){
			properties.put(key, good.getProperties().get(key));
		}
		snapshot.setProperties(properties);
		snapshot.setPublishTime(good.getPublishTime());
		snapshot.setQuantity(good.getQuantity());
		snapshot.setRateOfIncrease(good.getRateOfIncrease());
		snapshot.setSellType(good.getSellType());
		snapshot.setState(good.getState());
		snapshot.setTypeName(good.getType().getName());
		snapshot.setUser(good.getUser());
		snapshot.setUseType(good.getUseType());
			
		beanOrderDao.save(snapshot);

		BeanOrderItem orderItem = new BeanOrderItem();
		orderItem.setQuantity(auction.getQuantity());
		orderItem.setSnapshot(snapshot);
		orderItem.setGood(good);
		orderItem.setOrder(order);
		orderItem.setState(0);
		beanOrderDao.save(orderItem);
			
		order.getItems().add(orderItem);
		
		//计费
		BigDecimal totalFee = new BigDecimal("0.00");
		for(BeanOrderItem item : order.getItems()){
			totalFee = totalFee.add(new BigDecimal(item.getQuantity()).multiply(item.getSnapshot().getPrice()));
		}
		order.setTotalFee(totalFee);
		
		List<BeanOrder> orders = new ArrayList<BeanOrder>();
		orders.add(order);
		auction.setState("2");
		return orders;
	}

	@Override
	public void createCancel(Long buyerId, Long orderId) {
		//会话与订单一致
		BeanOrder order = beanOrderDao.findById(orderId, BeanOrder.class);
		if(order.getBuyer().getId() == buyerId){
			order.setState(IBeanOrderService.Constant.STATE_CANCELED);
		}
		
	}


}
